import { UploadRawFile } from 'element-plus'
import * as XLSX from 'xlsx'

export const useReadExcelFile = (file?: UploadRawFile) => {
    const data = ref([])
    const reader = new FileReader()
    reader.onload = function (ev: ProgressEvent<FileReader>) {
        const fileData = ev?.target?.result
        if (fileData) {
            const workbook = XLSX.read(fileData, { type: 'binary' })
            // 假设第一个工作表是所需的数据表
            const first_sheet_name = workbook.SheetNames[0]
            // 将工作表转换为JSON格式
            const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[first_sheet_name])
            let stringData = JSON.stringify(excelData)
            stringData = stringData.replace(/（/g, '(')
            stringData = stringData.replace(/）/g, ')')
            data.value = JSON.parse(stringData)
        }
    }
    reader.readAsArrayBuffer(file)

    return { data }
}
